package com.galaxy.commom.base.aop;


import com.alibaba.fastjson.JSON;
import com.galaxy.commom.base.utils.DateUtil;
import com.galaxy.commom.base.utils.IpUtil;
import com.galaxy.commom.base.utils.RegexUtil;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * web日志切面
 * @author caijinbang
 * @date 2018/9/7 20:51
 */
@Aspect
@Component
public class WebLogAspect {

  private Logger logger = LoggerFactory.getLogger("access");

  /**
   * 开始时间
   */
  private long startTime = 0L;

  @Pointcut("execution(* *..controller..*.*(..))")
  public void webLogPointCut() {

  }

  @Around("webLogPointCut()")
  public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    startTime = System.currentTimeMillis();
    //异常标记
    boolean eFlag = false;
    //获取请求对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    //拼接请求日志
    StringBuffer logSb = appendLogStrPre(pjp, request);
    Object result = null;
    try {
      result = pjp.proceed();
    } finally {
      //拼接返回日志
      String logStr = appendLogStrAfter(logSb, result);
      logger.info(logStr);
    }
    return result;
  }

  /**
   * 记录下请求内容
   *
   * @param pjp
   * @param request
   * @return StringBuffer
   * @author wanyong
   * @date 2017-12-12 11:07
   */
  private StringBuffer appendLogStrPre(ProceedingJoinPoint pjp, HttpServletRequest request) {
    startTime = System.currentTimeMillis();
    StringBuffer logSb = new StringBuffer();
    logSb.append("URL:").append(request.getRequestURL());
    logSb.append(",IP:").append(IpUtil.getIpAddress(request));
    logSb.append(",CLASS_METHOD:").append(pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
    logSb.append(",ARGS:").append(JSON.toJSONString(pjp.getArgs()).replaceAll(RegexUtil.getJSonValueRegex("password"),"****").replaceAll(
        RegexUtil.getJSonValueRegex("oldPassword"),"****"));
    return logSb;
  }

  /**
   * 处理完请求，返回内容
   *
   * @param logbf
   * @param result
   * @return String
   * @author wanyong
   * @date 2017-12-12 11:08
   */
  private String appendLogStrAfter(StringBuffer logbf, Object result) {
    logbf.append(",RESPONSE:").append(JSON.toJSONString(result).replaceAll(com.galaxy.commom.base.utils.RegexUtil.getJSonValueRegex("password"),"****"));
    logbf.append(",START_TIME:").append(DateUtil.getCurrentDateTime());
    logbf.append(",SEPEND_TIME:").append(System.currentTimeMillis() - startTime + "ms}");
    return logbf.toString();
  }

}
